import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../components/Home.vue'
import Blog from '../components/Blog.vue'
import TimeLine from '../components/TimeLine.vue'
import About from '../components/About.vue'
import article from '../components/Blog/article.vue'
import Category from '../components/Category.vue'
import Admin from '../components/Admin.vue'
import BsHome from '../components/Backstage/BsHome.vue'
import ArticleRelease from '../components/Backstage/ArticleRelease.vue'
import ArticleManagement from '../components/Backstage/ArticleManagement.vue'
import CommentManagement from '../components/Backstage/CommentManagement.vue'
import TimeRecord from '../components/Backstage/TimeRecord.vue'

Vue.use(VueRouter)

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/Blog',
    name: 'Blog',
    component: Blog
  },
  {
    path: '/Blog/article/:id',
    name: 'Blog/article',
    component: article
  },
  {
    path: '/TimeLine',
    name: 'TimeLine',
    component: TimeLine
  },
  {
    path: '/About',
    name: 'About',
    component: About
  },
  {
    path: '/Category',
    name: 'Category',
    component: Category
  },
  {
    path: '/Admin',
    name: 'Admin',
    component: Admin
  },
  {
    path: '/BsHome',
    name: 'BsHome',
    component: BsHome
  },
  {
    path: '/BsHome/ArticleRelease',
    name: 'ArticleRelease',
    component: ArticleRelease
  },
  {
    path: '/BsHome/ArticleManagement',
    name: 'ArticleManagement',
    component: ArticleManagement
  },
  {
    path: '/BsHome/CommentManagement',
    name: 'CommentManagement',
    component: CommentManagement
  },
  {
    path: '/BsHome/TimeRecord',
    name: 'TimeRecord',
    component: TimeRecord
  }
]

const router = new VueRouter({
  routes
})

// 使用路由导航守卫来确认用户的token值是否存在浏览器中
router.beforeEach((to, from, next) => {
  if (to.path === '/Admin') return next()
  const token = window.sessionStorage.getItem('token')
  if (!token && to.path === '/BsHome') {
    return next('/Admin')
  }
  next()
})

router.afterEach((to, from, next) => {
  window.scrollTo(0, 0)
})

export default router
